# -*- coding: utf-8 -*-
"""
@Time ：2021/4/6 21:20 
@Auth ： Mr. William 1052949192
@Company ：特斯汀学院 @testingedu.com.cn
@Function ：APP自动化关键字库
"""
import json
import os
import threading
import time

from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction


class App:
    """APP关键字库"""

    def __init__(self):
        self.port = '4723'
        self.driver: webdriver.Remote = None

    def runappium(self, appiumpath="E:\Appium-1.9", port='4723'):
        """多线程执行appium服务"""
        if appiumpath is None or appiumpath == '':
            appiumpath = "E:\Appium-1.9"

        if port is None or port == '':
            port = '4723'

        self.port = port
        appiumpath += r"\resources\app\node_modules\appium\build\lib\main.js --port " + port

        def run_appium(appium_path):
            """
            定义一个函数，专门处理这个阻塞的业务
            :param appium_path: appium的路径
            :return:
            """
            # 当我们启动appium服务器的时候，阻塞了主线程
            os.system("node " + appium_path)

        th = threading.Thread(target=run_appium, args=(appiumpath,))
        th.start()
        # 等待appium启动完成
        time.sleep(5)

    def runapp(self, conf: str = ''):
        """通过配置启动app"""
        # 把json字符串配置，处理为字典
        conf = json.loads(conf)
        # 需要连接appium，然后才能回放
        self.driver = webdriver.Remote("http://127.0.0.1:%s/wd/hub" % self.port, conf)
        # 等待app启动完成
        time.sleep(6)
        # 添加隐式等待
        self.driver.implicitly_wait(10)

    def killappium(self):
        """结束appium服务"""
        os.system('taskkill /F /IM node.exe')

    def __find_ele(self, locator: str = ''):
        """
        元素定位，支持三种方式
        :param locator: accessibility_id，id，xpath
        :return:
        """
        if locator.__contains__(':id/'):
            """id定位"""
            ele = self.driver.find_element_by_id(locator)
        elif locator.startswith('/'):
            # xpath定位
            ele = self.driver.find_element_by_xpath(locator)
        else:
            ele = self.driver.find_element_by_accessibility_id(locator)

        return ele

    def click(self, locator=''):
        """点击"""
        ele = self.__find_ele(locator)
        ele.click()

    def input(self, locator='', value=''):
        """输入文本"""
        ele = self.__find_ele(locator)
        ele.click()
        ele.clear()
        ele.send_keys(value)

    def sleep(self, t='1'):
        """等待"""
        try:
            t = float(t)
        except:
            t = 1
        time.sleep(float(t))

    def quit(self):
        self.driver.quit()

    def back(self, t='1'):
        """返回键"""
        try:
            t = float(t)
        except:
            t = 1
        self.driver.back()
        time.sleep(t)
